package com.xhorse.lockplatform.controller;

import com.xhorse.lockplatform.annotation.RequestLimit;
import com.xhorse.lockplatform.comm.constant.ConstantDefineUtil;
import com.xhorse.lockplatform.comm.constant.FilePathDefine;
import com.xhorse.lockplatform.comm.enums.ResultEnum;
import com.xhorse.lockplatform.comm.exception.LockPlatFormException;
import com.xhorse.lockplatform.comm.model.BaseMessage;
import com.xhorse.lockplatform.comm.model.BaseQuery;
import com.xhorse.lockplatform.comm.util.Paginator;
import com.xhorse.lockplatform.model.XhAppUpdateInfo;
import com.xhorse.lockplatform.service.AppUpdateInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("AppVersion")
public class AppVersionController {

    @Autowired
    private AppUpdateInfoService getUpdateInfoService;

    /**
     * 获取更新版本信息
     *
     * @param build
     * @param type
     * @param languageId
     * @return
     */
    @RequestMapping(value = "/getUpdateInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getUpdateInfo(String build, int type,
                                             int languageId) {
        Map<String, Object> result = getUpdateInfoService.getUpdateInfo(build,
                type, languageId);
        return result;
    }

    /**
     * apk应用内下载
     *
     * @param request
     * @param response
     */
    @RequestLimit(count = 3, time = 60000)
    @RequestMapping(value = "/apkDownload", method = {RequestMethod.POST, RequestMethod.GET})
    public void apkDownload(HttpServletRequest request,
                            HttpServletResponse response) {
        long downloaded = Long.valueOf(request.getParameter("downloaded"));
        String build = request.getParameter("build");
        int type = Integer.valueOf(request.getParameter("type"));
        String filename = "keytool.apk";
        Paginator page = new Paginator();
        AppUpdateInfoQuery query = new AppUpdateInfoQuery();
        query.setBuild(Integer.valueOf(build));
        query.setType(type);
        page.setQuery(query);
        List<XhAppUpdateInfo> list = getUpdateInfoService.selectByParam(page);
        if (!list.isEmpty()) {
            filename = list.get(0).getFileName();
        }
        File file = new File(FilePathDefine.APK_DOWNLOAD_PATH + filename);
        RandomAccessFile randomAccessFile = null;
        OutputStream outputStream = null;
        if (file.exists()) {
            response.setContentLength(new Long(file.length()).intValue());
            try {
                randomAccessFile = new RandomAccessFile(
                        FilePathDefine.APK_DOWNLOAD_PATH + filename, "r");
                randomAccessFile.seek(downloaded);
                outputStream = response.getOutputStream();
                byte[] b = new byte[1024 * 1024];
                int index;
                while ((index = randomAccessFile.read(b)) != -1) {
                    outputStream.write(b, 0, index);
                }
            } catch (FileNotFoundException e) {
                throw new LockPlatFormException(ResultEnum.FAILED.getCode(), "apkDownload FileNotFoundException，遇到异常", e);
            } catch (IOException e) {
                throw new LockPlatFormException(ResultEnum.FAILED.getCode(), "apkDownload IOException，遇到异常", e);
            } finally {
                try {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                    if (randomAccessFile != null) {
                        randomAccessFile.close();
                    }
                } catch (IOException e) {
                    throw new LockPlatFormException(ResultEnum.FAILED.getCode(), "apkDownload IOException，遇到异常", e);
                }

            }
        }
    }

    /**
     * 测试日志保存
     *
     * @param multipartFile
     * @return
     */
    @RequestLimit(count = 6, time = 60000)
    @RequestMapping(value = "/testLogUpload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> TestLogUpload(MultipartFile multipartFile,
                                             String customerId, int type) throws IOException { // type 1:crash 2:log
        BaseMessage baseMessage = new BaseMessage();
        File direcotry = new File(FilePathDefine.TEST_LOG_PATH + customerId
                + "\\");
        if (!direcotry.exists()) {
            direcotry.mkdirs();
        }
        SimpleDateFormat spd = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        String filename = customerId + "_" + type + "_" + spd.format(new Date()) + "_Log.txt";
        File file = new File(direcotry, filename);
        multipartFile.transferTo(file);
        baseMessage.putStatus(ConstantDefineUtil.STATUS.get("SUCCESS"));
        return baseMessage.baseMsg;
    }


    private static class AppUpdateInfoQuery extends BaseQuery {

        private int type;
        private int build;
        private int languageId;

        public void setType(int type) {
            this.type = type;
            this.addItem("type", type);
        }

        public void setBuild(int build) {
            this.build = build;
            this.addItem("build", build);
        }

        public void setLanguageId(int languageId) {
            this.languageId = languageId;
            this.addItem("languageId", languageId);
        }
    }
}
